package com.opennews.openplatform

import grails.compiler.GrailsCompileStatic
import grails.gorm.transactions.Transactional
import groovy.transform.CompileDynamic
import org.hibernate.criterion.CriteriaSpecification
import org.springframework.beans.factory.annotation.Value

@Transactional(readOnly = true)
@GrailsCompileStatic
class BankService {
    @Value('${openplatform.resource.httpBaseUrl}')
    String httpBaseUrl

    @Value('${openplatform.resource.bankLogoUrl}')
    String bankLogoUrl

    /**
     * Prepares the initial data for Bank and BankCard.
     */
    @Transactional
    void init() {
        if (Bank.count() == 0) {
            // Related info for CCB (China Construction Bank).
            def bank = new Bank(name: "上海银行", shortName: "BOSC").save()

            // Related info for CCB (China Construction Bank).
            bank = new Bank(name: "建行", shortName: "CCB").save()

            // The bank cards for CCB.
            // new BankCard(bank: bank, name: "ETC", statementDate: "5",
            //     paymentDueDate: "24", customerServiceNumber: "400-820-0588 / 021-3869-0588").save()

            // Related info for CMBC (China Merchants Bank).
            bank = new Bank(name: "交行", shortName: "BCM").save()

            // Related info for CMBC (China Merchants Bank).
            bank = new Bank(name: "招行", shortName: "CMB").save()

            // The bank cards for CMBC.
            // new BankCard(bank: bank, name: "双币", statementDate: "16",
            //     paymentDueDate: "+3", customerServiceNumber: "400-820-5555 / 021-3878-4800").save()
        }
    }

    /**
     * Gets bank logo url based on its short name.
     * @param shortName: The bank short name.
     * @return The full url of the bank logo.
     */
    String getLogoUrl(String shortName) {
        return !SharedUtil.isNullOrEmpty(shortName) ? "$httpBaseUrl$bankLogoUrl/${shortName.toLowerCase()}.png" : ""
    }

    /**
     * Queries all banks with basic info.
     * @return List of map instance which contains keys below.
     *          id: String of bank id.
     *          name: String of bank name.
     *          shortName: String of bank short name.
     */
    @CompileDynamic
    List<Map<String, ?>> queryAllWithBasicInfo() {
        return Bank.createCriteria().list {
            // Transforms the result data format to Map instance.
            resultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP)

            // Specifies the property we need.
            projections {
                property("id", "id")
                property("name", "name")
                property("shortName", "shortName")
            }
        }.each { Map<String, ?> item ->
            // Adds logoUrl key to this map item.
            item.logoUrl = getLogoUrl(item.shortName.toString())
        } as List<Map<String, ?>>
    }
}